//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Microsoft.Research.DataLayer;
using System.Globalization;

namespace Webhost
{
    /// <summary>
    /// Summary description for GetWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class GetWebService : System.Web.Services.WebService
    {

        private const string DEFAULT_WEB_SERVICE_NAME = "http://{0}:{1}/TridentRegistryWebService";

        /// <summary>
        /// Gets the web service URI for the silverlight client
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string GetWebServiceURI()
        {
            string webHostUri = HttpContext.Current.Request.Url.OriginalString.Substring(0, HttpContext.Current.Request.Url.OriginalString.LastIndexOf("/", StringComparison.Ordinal));
            string webServiceUri = string.Empty;
            try
            {
                WebServiceLocation.ISearch search = WebServiceLocation.ISearch.Create();
                WebServiceLocation.ISearch.ISearchClause searchClause = WebServiceLocation.ISearch.SilverlightURI(StringField.Condition.Contains, webHostUri);
                search.Query = searchClause;
                List<WebServiceLocation> searchResult = WebServiceLocation.Search(search, Global.RegistryConnection);

                if (searchResult.Count > 0)
                {
                    webServiceUri = searchResult[0].WebServiceURI;
                }
                else
                {
                    webServiceUri = string.Format(CultureInfo.InvariantCulture, DEFAULT_WEB_SERVICE_NAME, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port);
                }
            }
            catch
            {
                webServiceUri = string.Format(CultureInfo.InvariantCulture, DEFAULT_WEB_SERVICE_NAME, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port);
            }
            return webServiceUri;
        }
    }
}
